﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class cms_AddNewGallery : System.Web.UI.Page
{
    string path = "~/images/Gallery/";
    private int Id = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["user"] == null)
        {
            Response.Redirect("Default.aspx");
        }
        if (!IsPostBack)
        {
            if (!string.IsNullOrEmpty(Request.QueryString["Id"]))
            {
                Id = Convert.ToInt32(Request.QueryString["Id"]);
                btnAdd.Text = "Update";
                //set info
                DBClass db = new DBClass();
                DataSet ds = db.GetAllGallery(Id);
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    DataRow dr = ds.Tables[0].Rows[0];
                    txtName.Text = Convert.ToString(dr["Name"]);
                    image.ImageUrl = path + Convert.ToString(dr["Image"]);
                    txtDescription.Text = Convert.ToString(dr["Description"]);
                    ddlType.SelectedValue = Convert.ToString(dr["TypeId"]);
                }
            }
            else
            {
                btnAdd.Text = "Add Now";
                image.Visible = false;
            }
        }
    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        DBClass db = new DBClass();
        if (!string.IsNullOrEmpty(Request.QueryString["Id"]))
        {
            Id = Convert.ToInt32(Request.QueryString["Id"]);
            string image = "";
            if (FileImage.HasFile)
            {
                image = Id + System.IO.Path.GetExtension(FileImage.FileName);
                FileImage.SaveAs(Server.MapPath(path + image));
            }
            db.UpdateGallery(Id, txtName.Text.Trim(), image, txtDescription.Text.Trim(), Convert.ToInt32(ddlType.SelectedValue));
        }
        else
        {
            string image = "";
            int i = db.InsertGallery(txtName.Text.Trim(), image, txtDescription.Text.Trim(), Convert.ToInt32(ddlType.SelectedValue));
            if (i > 0 && FileImage.HasFile)
            {
                image = i + System.IO.Path.GetExtension(FileImage.FileName);
                FileImage.SaveAs(Server.MapPath(path + image));
                db.UpdateGallery(i, txtName.Text, image, txtDescription.Text, Convert.ToInt32(ddlType.SelectedValue));
            }
        }
        Response.Redirect("ListGallery.aspx");
    }
}